package com.ego.dubbo.service.impl;

import com.ego.commons.exception.DaoException;
import com.ego.dubbo.service.TbOrderDubboService;
import com.ego.mapper.TbItemMapper;
import com.ego.mapper.TbOrderItemMapper;
import com.ego.mapper.TbOrderMapper;
import com.ego.mapper.TbOrderShippingMapper;
import com.ego.pojo.TbItem;
import com.ego.pojo.TbOrder;
import com.ego.pojo.TbOrderItem;
import com.ego.pojo.TbOrderShipping;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Title
 * @Author Lyg
 * @Description:
 */
@DubboService
public class TbOrderDubboServiceImpl implements TbOrderDubboService {

    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;

    @Autowired
    private TbOrderShippingMapper tbOrderShippingMapper;


    @Autowired
    private TbItemMapper tbItemMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(TbOrder tbOrder, List<TbOrderItem> orderItemList, TbOrderShipping tbOrderShipping) throws DaoException {
        try {
            int index = 0;
            index = tbOrderMapper.insert(tbOrder);

            if (index==1){
                int index2 = 0;
                //循环订单商品，分别设置对应的订单id，并新增到数据库
                for (TbOrderItem tbOrderItem : orderItemList) {
                    index2+= tbOrderItemMapper.insert(tbOrderItem);

                    //根据下单商品id查询出对应的商品
                    String itemId = tbOrderItem.getItemId();
                    TbItem tbItem = tbItemMapper.selectByPrimaryKey(Long.valueOf(itemId));
                    //修改数量
                    tbItem.setNum(tbItem.getNum()-tbOrderItem.getNum());

                    index2 += tbItemMapper.updateByPrimaryKeySelective(tbItem);
                }
                int index3=0;
                //新增收货地址
                if(index2==(orderItemList.size()*2)){
                    index3 = tbOrderShippingMapper.insert(tbOrderShipping);
                }
                return index3;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            throw new DaoException("新增订单失败");
        }
        return 0;
    }
}
